﻿Function Get-WhiteSpace([string]$server, [string]$MailboxDatabaseName, [array]$WSEvents) {
	$Array = @()
	$Result = @()
	$WSpace = $WSEvents | Where-Object {$_.Message.Contains($MailboxDatabaseName)}
	#$Check = $WSpace -is [array]
	If ($WSpace -is [array]) {
		Write-Host 'WSpace is Array?: ' ($WSpace -is [array])
		ForEach ($item in $WSpace) {
			$Array = $item.message.split("`"")
			$EndString = $Array[2].indexof("megabytes ")-6
			#write-host $mbnamearray[1]
			[int]$Result = $Array[2].Substring(5,$EndString)
		}
	} else {
		Write-Host 'WSpace is Array?: ' ($WSpace -is [array])
		If ($WSpace -ne $null) {
			$Array = $WSpace.message.split("`"")
			$EndString = $Array[2].indexof("megabytes ")-6
			#write-host $mbnamearray[1]
			[int]$Result = $Array[2].Substring(5,$EndString)
		} else {
			$Result = "No defrag last day"
		}
	}
	$Result
} #end of Function Get-Whitespace
$ServerSkipList = "C:\WINDOWS\Scripts\ExServersToSkip.csv"

$skiplist = @()
Import-Csv $ServerSkipList | ForEach-Object {$skiplist += $_.Servername}


$exchange2007servers = @(Get-MailboxServer | Where-Object {$skiplist -notcontains $_.name} | Sort-Object Name | Select-Object Name) 
#$exchange2003servers = @(Get-ExchangeServer | Where-Object {$skiplist -notcontains $_.name -and $_.admindisplayversion.major -ne 8 } | Sort-Object Name | Select-Object Name)
$exchangeServers = $exchange2003servers + $exchange2007servers
$DatabaseInfo=@()
#---------------8<---------------Function Main Exchange 2007
foreach ($server in $exchangeServers) {
	Write-Host "======================"
	$server.name
	Write-Host "Getting Mailbox Databases"
	$ServerDatabases = Get-MailboxDatabase -Status -server $server.name | Where-Object {$_.Name -ne "Mailbox Database"} | Sort-Object
		If ($ServerDatabases -ne $null) {
			$Volumes = Get-WMIObject Win32_Volume -computerName $server.name #pulled this here so it only runs once per server
			Write-Host "Getting 1221 events"
			$WhiteSpaceEvents = Get-EventLog -ComputerName $server.name -log Application -Source "MsExchangeIS Mailbox Store" -EntryType Information -after (get-date).addHours(-36) | Where-Object {$_.EventID -eq 1221 } 
			Write-Host "Time to retrieve events: " + $GetEventTime.TotalMinutes
			foreach ($MailboxDatabase in $ServerDatabases) {
				$dbdata = New-Object PSObject
	
				Write-Host "*****************"
				$L20 = $null
				$L30 = $null
				$DiskCapacity = $null
				$FreeOnStorage = $null
				$FreeOnStorageProc = $null
				$MDBSize = $null
				$WhiteSpace =$null
				$MBXCount = $null
				$BackupDays = $null
				
				Write-Host "DatabaseName: " $MailboxDatabase.name
				$edbfilepath = $MailboxDatabase.edbfilepath.ToString()
				Write-Host '$edbpath: ' $edbfilepath.ToUpper()
				#convert absolute path to UNC path
				$path = "`\`\" + $server.name + "`\" + $MailboxDatabase.EdbFilePath.DriveName.Remove(1).ToString() + "$"+ $MailboxDatabase.EdbFilePath.PathName.Remove(0,2)
				Write-Host '$path: ' $path
				$dbsize = Get-ChildItem $path
				#Write-Host '$dbsize: ' $dbsize
				####mailboxcount different
				$mailboxcount = Get-MailboxStatistics -database "$MailboxDatabase" | measure-object
				#$mailboxcount = Get-MailboxDatabase -Server $server.name | where { $_.Name -eq $MailboxDatabase.name } | Get-Mailbox -ResultSize:Unlimited | measure-object
				
				$edbpathlength = 0
				#$volumes = Get-WMIObject Win32_Volume -computerName $server.name  #does not need to run more than once per server
				foreach ($volItem in $Volumes) {
					If ( $edbfilepath.ToUpper().startswith($volItem.name.ToUpper()) ) {
						write-host $volItem.name.ToUpper() "   -   " $edbfilepath.startswith($volItem.name) "   -   " $volItem.name.length			
						If ($edbpathlength -lt $volItem.name.length) {	
							$edbpathlength = $volItem.name.length
							$edbfilepathvolumename = $volItem.name
							$edbfilepathfreespace =  $volItem.freespace
							$edbfilepathcapacity = $volItem.capacity
						}
					}
				}
				
				$VolumeName = $edbfilepathvolumename
				$FreeOnStorage = "{0:N2}" -f ($edbfilepathfreespace/1GB)
				$DiskCapacity = "{0:N2}" -f ($edbfilepathcapacity/1GB)

				Write-Host '$VolumeName: ' $VolumeName
				Write-Host '$DiskCapacity: ' $DiskCapacity
				Write-Host '$FreeOnStorage: ' $FreeOnStorage
				$FreeOnStoragePercent = ([int] $FreeOnStorage / [int] $DiskCapacity)
				$FreeOnStoragePercent = [int] ($FreeOnStoragePercent * 100)
				Write-Host '$FreeOnStoragePercent2: ' $FreeOnStoragePercent
				$MDBSize = ("{0:N2}" -f ($dbsize.Length/1GB))
				Write-Host 'MDBSize: ' $MDBSize
				$MBXCount = $mailboxcount.count
				$LastBackup = $MailboxDatabase.LastFullBackup
				Write-Host '$LastBackup: ' $LastBackup
				$WhiteSpace = Get-WhiteSpace $server.name $MailboxDatabase.name $WhiteSpaceEvents
				Write-Host '$WhiteSpace: ' $WhiteSpace
				
				$L20 = [int] $MDBSize * 1024 * .2
				$L30 = [int] $MDBSize * 1024 * .3
				Write-Host '$L20: ' $L20
				Write-Host '$L30: ' $L30
				$dbdata | Add-Member -MemberType NoteProperty -Name Servername -Value $server.name
				$dbdata | Add-Member -MemberType NoteProperty -Name DatabaseName -Value $MailboxDatabase.name
				$dbdata | Add-Member -MemberType NoteProperty -Name Path -Value $path
				
				$dbdata | Add-Member -MemberType NoteProperty -Name DBSize -Value $MDBSize
				$dbdata | Add-Member -MemberType NoteProperty -Name Mailboxes -Value $mailboxcount.count
				$dbdata | Add-Member -MemberType NoteProperty -Name DiskCapacity -Value $DiskCapacity
				$dbdata | Add-Member -MemberType NoteProperty -Name FreeOnStorage -Value $FreeOnStorage
				$dbdata | Add-Member -MemberType NoteProperty -Name PercentFree -Value $FreeOnStoragePercent
				$dbdata | Add-Member -MemberType NoteProperty -Name Whitespace -Value $WhiteSpace
				$DatabaseInfo += $dbdata
			}
		}
		
}  # End of Main Exchange 2007/2003 loop

Export-Csv -NoTypeInformation ExDatabaseInfo.csv